﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Common
{
    public sealed class Cookie
    {
        /// <summary>
        /// 增加或修改HttpCookie的值
        /// </summary>
        /// <param name="strCName">HttpCookie的名称</param>
        /// <param name="strCValue">HttpCookie的数值</param>
        /// <returns>无</returns>
        public static void _WriteHttpCookie(string strCName, string strCValue)
        {
            if (System.Web.HttpContext.Current.Request.Cookies[strCName] != null)
            {
                System.Web.HttpContext.Current.Response.Cookies.Remove(strCName);
            }

            System.Web.HttpCookie ck = new HttpCookie(strCName);
            ck.Expires = System.DateTime.Now.AddDays(30); //设置30天过期
            ck.Value = System.Web.HttpUtility.UrlEncode(strCValue);
            System.Web.HttpContext.Current.Response.Cookies.Add(ck);
        }

        /// <summary>
        /// 读取HttpCookie的值
        /// </summary>
        /// <param name="strCName">HttpCookie的名称</param>
        /// <returns>返回HttpCookie的数值</returns>
        public static string _ReadHttpCookie(string strCName)
        {
            string strResult = "";
            if (System.Web.HttpContext.Current.Request.Cookies[strCName] != null)
            {
                strResult = System.Web.HttpUtility.UrlDecode(System.Web.HttpContext.Current.Request.Cookies[strCName].Value);
            }

            return strResult;
        }

        /// <summary>
        /// 删除指定HttpCookie
        /// </summary>
        /// <param name="strCName">HttpCookie的名称</param>
        /// <returns>无</returns>
        public static void _DeleteHttpCookie(string strCName)
        {
            if (System.Web.HttpContext.Current.Request.Cookies[strCName] != null)
            {
                System.Web.HttpContext.Current.Response.Cookies.Remove(strCName);
            }
        }


        /// <summary>
        /// 清除所有的HttpCookie
        /// </summary>
        /// <returns>无</returns>
        public static void _ClearHttpCookie()
        {
            try
            {
                HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["c_code"];
                cookie.Expires = DateTime.Today.AddDays(-10);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

            }
            catch
            {

            }

        }

    }
}
